<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\lists\room;


use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\service\DataHandleService;
use app\common\lists\ListsExcelInterface;
use app\common\lists\ListsSearchInterface;
use app\common\model\room\RoomHospital;
use app\common\model\room\RoomHospitalLog;
use app\common\model\room\RoomHospitalUser;
use think\facade\Db;


/**
 * 全院住户导出(季度)列表
 * Class RoomHospitalUserExportSeason
 * @package app\adminapi\listsroom
 */
class RoomHospitalUserExportSeason extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface {

    protected $export_name = '导出';
    protected $export_lists = [];
    protected $export_fields = [];
    protected $lists_month = 3; // 个月

    public function setting($name, $val) {
        $this->$name = $val;
    }

    /**
     * @notes 设置搜索条件
     */
    public function setSearch(): array {
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);
        $m_arr = DataHandleService::getQuarterTime($year, $month);

        $where = $where_log = [];
        if ($this->lists_month == 3) {
            if ($search_month == date("Ym")) {
//            $where[] = ["log_date", "in", $m_arr[$month]];
            }
            $where_log[] = ["log_date", "in", $m_arr[$month]];
        }

        $param = $this->request->param();

        if (!empty($this->adminCid) && $this->adminCid !== 0) {
            $where[] = ['cid', '=', $this->adminCid];
        }
        if (!empty($param['cb_ids'])) {
            if (!empty($param['cb_ids'][0])) {
                $where[] = ['cid', '=', $param['cb_ids'][0]];
                $where_log[] = ['cid', '=', $param['cb_ids'][0]];
            }
            if (!empty($param['cb_ids'][1])) {
                $where[] = ['bid', '=', $param['cb_ids'][1]];
                $where_log[] = ['bid', '=', $param['cb_ids'][1]];
            }
        }

        if (isset($param['room_keyword']) && $param['room_keyword'] != '') {
            $where[] = ['name|address', 'like', '%' . $param['room_keyword'] . '%'];
            $where_log[] = ['name|address', 'like', '%' . $param['room_keyword'] . '%'];
        }

        if (isset($param['user_keyword']) && $param['user_keyword'] != '') {
            $where[] = ['user_name|user_mobile', 'like', '%' . $param['user_keyword'] . '%'];
            $where_log[] = ['user_name|user_mobile', 'like', '%' . $param['user_keyword'] . '%'];
        }

        if (isset($param['room_type']) && $param['room_type'] != '') {
            $where[] = ["type", "=", $param['room_type']];
            $where_log[] = ["type", "=", $param['room_type']];
        }

        return [
            "where" => $where,
            "where_log" => $where_log,
        ];
    }

    /**
     * @notes 获取科室用户关联列表
     */
    public function lists(): array {
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);
        if ($month % 3 == 1) {
            $season_month = [$month * 1, $month * 1 + 1, $month * 1 + 2];
        } elseif ($month % 3 == 2) {
            $season_month = [$month * 1 - 1, $month * 1, $month * 1 + 1];
        } else {
            $season_month = [$month * 1 - 2, $month * 1 - 1, $month * 1];
        }

        if ($this->lists_month == 1) {
            $log_data_text = $year . '年' . $month . '月';
        } else {
            $log_data_text = $year . '年'
                . str_pad($season_month[0], 2, '0', STR_PAD_LEFT) . '+'
                . str_pad($season_month[1], 2, '0', STR_PAD_LEFT) . '+'
                . str_pad($season_month[2], 2, '0', STR_PAD_LEFT) . '月';
        }

        $data = [
            "db" => new \think\Db(),
        ];
        $union = [];

        if ($search_month == date("Ym") || (in_array(date("m"), $season_month) && $this->lists_month == 3)) {
            $union[] = RoomHospital::field([
                "id as rid", "name as room_name", "sort",
                "'" . $search_month . "' as log_date", "'" . $log_data_text . "' as time_text",
                "room_department", "room_department_sort",
                "user_id", "user_name", "user_mobile",
                "lift_fee as room_lift_fee", "second_pressure_fee as room_second_pressure_fee",
//                "room_s_use_total", "room_s_price", "room_s_total_fee",
//                "room_d_use_total", "room_d_price", "room_d_total_fee",
//                "room_all_total_fee",
            ])->where($this->setSearch()['where'])
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_s_use_total';
                    $query->where('device_type', 1);
                }], "use_total")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_s_price';
                    $query->where('device_type', 1);
                }], "price")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_s_total_fee';
                    $query->where('device_type', 1);
                }], "total_fee")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_d_use_total';
                    $query->where('device_type', 2);
                }], "use_total")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_d_price';
                    $query->where('device_type', 2);
                }], "price")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_d_total_fee';
                    $query->where('device_type', 2);
                }], "total_fee")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_all_total_fee';
                }], "total_fee")
                ->buildSql();
//                ->select()->toArray();

//            $lists1 = (new RoomHospitalUserLists())->lists();
//            $union = array_merge($union, $lists1);
        }

        $lists = RoomHospitalLog::field([
            "rid", "name as room_name", "sort",
            "log_date", "'" . $log_data_text . "' as time_text",
            "room_department", "room_department_sort",
            "user_id", "user_name", "user_mobile",
            "room_lift_fee", "room_second_pressure_fee",
            "room_s_use_total", "room_s_price", "room_s_total_fee",
            "room_d_use_total", "room_d_price", "room_d_total_fee",
            "room_all_total_fee",
        ])->where($this->setSearch()['where_log']);
        if (count($union) > 0) {
            $lists = $lists->unionAll($union);
        }
        $lists = $lists->order([
            $data['db']->raw("field(room_department, '空房') asc"), // 科室排序 * 在最后
            $data['db']->raw('convert(room_department using gbk) asc'), // 先进行科室排序
            "sort asc", // 楼栋排序
        ])->select()->toArray();

        $lists = array_map(function ($item) use ($data) {
            $item['room_department'] = empty($item['room_department']) ? '空' : $item['room_department'];

            $item['room_s_use_total'] = $item['room_s_use_total'] * 1;
            $item['room_s_price'] = $item['room_s_price'] * 1;
            $item['room_s_total_fee'] = $item['room_s_total_fee'] * 1;
            $item['room_d_use_total'] = $item['room_d_use_total'] * 1;
            $item['room_d_price'] = $item['room_d_price'] * 1;
            $item['room_d_total_fee'] = $item['room_d_total_fee'] * 1;
            $item['room_all_total_fee'] = $item['room_all_total_fee'] * 1;

            return $item;
        }, $lists);

        return $lists;

//        $lists = RoomHospitalUser::field([
//            "user_id", "user_name", "user_mobile", "log_date", // "room_department",
//            "all_lift_fee", "all_second_pressure_fee",
//            "all_s_use_total", "all_s_total_fee", // "all_s_price",
//            "all_d_use_total", "all_d_total_fee", // "all_d_price",
//            "all_total_fee",
//        ])->where($this->setSearch()['where_log'])->select()->toArray();
//        $union = array_merge($union, $lists);
//        // $union = array_column($union, 'name'); // 重新设置key
//        $user_lists = [];
//        $user_value = [
//            "user_name" => null,
//            "user_mobile" => null,
//            "room_department" => '空',
//            "all_lift_fee" => 0, "all_second_pressure_fee" => 0,
//            "all_s_use_total" => 0, "all_s_total_fee" => 0,
//            "all_d_use_total" => 0, "all_d_total_fee" => 0,
//            "all_total_fee" => 0,
//        ];
//        foreach ($union as $k => &$v) {
//            $v['all_total_fee'] = 1 * sprintf("%.2f", $v['all_total_fee']);
//
//            if (empty($user_lists[$v['user_id']])) {
//                $user_lists[$v['user_id']] = $user_value;
//            }
//            $user_lists[$v['user_id']] = [
//                "month_time" => $log_data_text,
//                "user_id" => $v['user_id'],
//                "user_name" => $user_lists[$v['user_id']]['user_name'] ?? $v['user_name'],
//                "user_mobile" => $user_lists[$v['user_id']]['user_mobile'] ?? $v['user_mobile'],
//                "room_department" => ($user_lists[$v['user_id']]['room_department'] == '空') ? ($v['room_department'] ?? '空') : '空',
//
//                "all_lift_fee" => 1 * $user_lists[$v['user_id']]['all_lift_fee'] + $v['all_lift_fee'],
//                "all_second_pressure_fee" => 1 * $user_lists[$v['user_id']]['all_second_pressure_fee'] + $v['all_second_pressure_fee'],
//                "all_s_use_total" => $user_lists[$v['user_id']]['all_s_use_total'] + $v['all_s_use_total'],
////                "all_s_price" => $user_lists[$v['user_id']]['all_s_price'] + $v['all_s_price'],
//                "all_s_total_fee" => $user_lists[$v['user_id']]['all_s_total_fee'] + $v['all_s_total_fee'],
//                "all_d_use_total" => $user_lists[$v['user_id']]['all_d_use_total'] + $v['all_d_use_total'],
////                "all_d_price" => $user_lists[$v['user_id']]['all_d_price'] + $v['all_d_price'],
//                "all_d_total_fee" => $user_lists[$v['user_id']]['all_d_total_fee'] + $v['all_d_total_fee'],
//                "all_total_fee" => 1 * sprintf("%.2f", $user_lists[$v['user_id']]['all_total_fee'] + 1 * $v['all_total_fee']),
//            ];
//        }
//        $user_lists = array_values($user_lists);
//        return $user_lists;
    }

    /**
     * 本月记录
     */
    public function this_time_lists() {


    }

    /**
     * 历史记录
     */
    public function log_time_lists() {

    }

    /**
     * @notes 获取科室用户关联数量
     */
    public function count(): int {
        return 100;
    }

    public function setExport($name, $lists, $fields) {
        $this->export_name = $name;
        $this->export_lists = $lists;
        $this->export_fields = $fields;
    }

    public function setFileName(): string {
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");

        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);

        $m_arr = DataHandleService::getQuarterMonth();

        return '全院住户信息表(季度)-' . $year . '年' . $m_arr[$month];
    }

    public function setExcelLists() {
        return $this->export_lists;
    }

    /**
     * @notes 导出字段
     * @return string[]
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelFields(): array {
        return $this->export_fields;
    }

}
